import { defineStore } from "pinia";
import { reactive } from "vue";
import { routes } from "@/router";
import router from "@/router";

//动态导入路由，import.meta.glob() 为vite提供的方法
let modules = import.meta.glob(`../../views/**/*.vue`)
let modules2 = import.meta.glob(`../../components/**/*.vue`)
function formatRoute(arr) {
  for (let index = 0; index < arr.length; index++) {
    const e = arr[index];
    if (e.component.slice(0, 1) == 'c') {
      e.component = modules2[`../../${e.component}`]
    } else {
      e.component = modules[`../../${e.component}`]
    }
    if (e.children) {
      formatRoute(e.children)
    }
  }
}
let userMenu = defineStore('menu', () => {
  let menuList = reactive([])
  function changeMenuList(e) {
    e.forEach(el => {
      menuList.push(el)
    })

  }
  function addRoute() {
    formatRoute(menuList)
    routes.forEach(e => {
      menuList.unshift(e)
    })
    menuList.forEach(e => {
      router.addRoute(e)
    })
  }
  function resetMenuList(e) {
    menuList = e
  }
  return {
    menuList,
    changeMenuList,
    addRoute,
    resetMenuList
  }
}, {
  persist: {
    enabled: true,
    strategies: [
      { storage: localStorage, paths: ['menuList'] },
    ],
  }
})

export default userMenu